const host = location.hostname;
const r1 = (regp, s) => regp.test(s) && RegExp.$1;
const sleep = ms => new Promise(resolve => { setTimeout(resolve, ms) });
const log = console.log.bind(console);
const q = (css, p = document) => p.querySelector(css);
const getExtName = url => {
	let i, n = url.indexOf('?', 21);
	if (-1 != n) i = n-3;
	else {
		i = url.length - 4;
		n = void 0;
	}
	i = url.lastIndexOf('.',i) +1;
	if (i) return url.slice(i, n);
};
const getPlayType = (url) => {
	const ext = getExtName(url);
	if (/mp4|ogg|webm/.test(ext)) return 'normal';
	if (ext == 'm3u8') return 'hls';
	if (ext == 'mpd') return 'dash';
	if (url.includes('/hls/', 11) || url.includes('m3u8', 7)) return 'hls';
	if (url.includes('.mp4', 25)) return 'normal';
	if (url.includes('.mpd', 25)) return 'dash';
	return 'auto';
};
const dom = new Proxy({}, {
	get(target, tag) {
		return function (attrs = {}, ...children) {
			const el = document.createElement(tag);
			for (let prop of Object.keys(attrs)) {
				el.setAttribute(prop, attrs[prop]);
			}
			for (let child of children) {
				if (typeof child === 'string') {
					child = document.createTextNode(child);
				}
				el.appendChild(child);
			}
			document.head.appendChild(el);
			return el;
		}
	}
});
const isMVFlash = e => {
	const isEmbed = e.matches('embed');
	let s = isEmbed ? e.src : (e.data || e.children.movie.value);
	if (!s || !/\.swf(?:$|\?)/.test(s)) return !1;
	if (e.offsetHeight > 99) return !0;
	if (isEmbed) return !1;
	s = q('embed', e);
	return !!(s && isMVFlash(s));
};
const iframes = document.getElementsByTagName('iframe');
const find = [].find.bind(iframes);

let autoWebFull, hostsDisableWF;
chrome.storage.sync.get({
	autoWebFull: true,
	hostsDisableWebFull: []
}, function(items) {
	hostsDisableWF = items.hostsDisableWebFull;
	autoWebFull = items.autoWebFull;
});

const createPlayer = async (v, url, type = 'auto') => {
	if (!type || type == 'auto') type = getPlayType(url);
	const dp = new DPlayer({
		video: { url, type },
		theme: "#00B3FF",
		autoplay: true,
		screenshot: true,
		contextmenu: [
			{
				text: '将当前域名加入白名单',
				click(player) {
					chrome.runtime.sendMessage({id:'add-domain-whitelist', host});
					if (!player.video.duration) location.reload();
				}
			},{
				text: '不能播放！转内置播放器',
				click(player) {
					player.pause();
					chrome.runtime.sendMessage({id:'native-play', url, vType: type});
				}
			}
		],
		container: v
	});
	dp.container.closest('body > *').classList.add('gm-dp-zTop');
	await sleep(99);
	let a = [], e = dp.video;
	while (e.offsetHeight < 199) {
		a.push(e);
		e = e.parentNode;
	}
	if (a.length > 0) a.pop().style.height = e.offsetHeight + 'px';
	await sleep(99);
	autoWebFull && !hostsDisableWF.some(k => host.includes(k)) && dp.fullScreen.request('web');
		// dp.container.scrollIntoView({block:'nearest',behavior:'smooth'});
};